package com.ym.jiujiangeyou;

import java.util.ArrayList;

import java.util.List;
import java.util.Map;

import com.ym.jiujiangeyou.adapter.SceneryListAdapter;
import com.ym.jiujiangeyou.app.AppManager;
import com.ym.jiujiangeyou.app.MyApplication;
import com.ym.jiujiangeyou.entity.Guide;
import com.ym.jiujiangeyou.entity.Scenery;
import com.ym.jiujiangeyou.entity.User;
import com.ym.jiujiangeyou.parse.ParseGson;
import com.ym.jiujiangeyou.ui.DialogView;
import com.ym.jiujiangeyou.ui.XListView;
import com.ym.jiujiangeyou.ui.XListView.IXListViewListener;
import com.ym.jiujiangeyou.util.ConfigCache;
import com.ym.jiujiangeyou.util.Constants;
import com.ym.jiujiangeyou.util.HttpUtil;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author 叶铭
 * @email yeming_1001@163.com
 * @version V1.0
 */
public class SceneryListActivity extends Activity implements IXListViewListener {

	private SceneryListAdapter adapter;
	private XListView listView;
	private Dialog dialog;
	private Toast toast;
	private ProgressBar lv_foot_progress;
	private TextView lv_foot_more;
	private View lv_footer;
	private Handler handler;
	private List<Guide> gNewlv, gCountlv, glist;
	private List<Scenery> sNewlv, sCountlv, slist;
	private Context context;
	private int status;
	private int count;
	private EditText scenery_search_text;
	private LinearLayout scenery_search;
	private boolean isFirst = false;
	TextView title_text;
	private LinearLayout title_back;
	private RelativeLayout rel_default_action;
	private int defaul_action = Constants.LISTVIEW_ACTION_FIRST;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加Activity到堆栈
		AppManager.getAppManager().addActivity(this);
		super.setContentView(R.layout.scenery);
		initResouce();
		if (gNewlv.isEmpty() || sNewlv.isEmpty()) {
			loadData(Constants.LISTVIEW_ACTION_FIRST, handler, 1);
		}

	}

	public void initResouce() {

		handler = new Handler() {
			@SuppressWarnings({ "unchecked", "unused" })
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				sNewlv.clear();
				gNewlv.clear();
				Map<String, Object> map;
				switch (msg.what) {
				case Constants.LISTVIEW_ACTION_FIRST:
					if (rel_default_action.getVisibility() == View.VISIBLE) {
						rel_default_action.setVisibility(View.GONE);
						rel_default_action.setClickable(false);
					}
					map = (Map<String, Object>) msg.obj;
					sNewlv = (List<Scenery>) map.get("scenery");
					gNewlv = (List<Guide>) map.get("guide");
					sCountlv.addAll(sNewlv);
					gCountlv.addAll(gNewlv);
					adapter.setData(sCountlv);
					count = sCountlv.size();
					listView.setAdapter(adapter);
					dialog.dismiss();
					break;
				case Constants.LISTVIEW_ACTION_SCROLL:
					map = (Map<String, Object>) msg.obj;
					int flag = (Integer) map.get("status");
					if (flag == 1) {
						sNewlv = (List<Scenery>) map.get("scenery");
						gNewlv = (List<Guide>) map.get("guide");

					} else if (flag == 0) {
						listView.nomore();
					}
					listView.stopLoadMore();
					sCountlv.addAll(sNewlv);
					gCountlv.addAll(gNewlv);
					count = sCountlv.size();
					adapter.setData(sCountlv);
					break;
				case Constants.LISTVIEW_ACTION_GET_ERROR:
					dialog.dismiss();
					if (defaul_action == Constants.LISTVIEW_ACTION_FIRST) {
						rel_default_action.setVisibility(View.VISIBLE);
						rel_default_action.setClickable(true);
					}
					toast = DialogView.popToast(context,
							R.string.http_connect_error);
					toast.show();
					break;
				case Constants.LISTVIEW_ACTION_SEARCH:
					map = (Map<String, Object>) msg.obj;
					sCountlv.clear();
					gCountlv.clear();
					int temp = (Integer) map.get("status");
					if (temp == 1) {
						isFirst = !isFirst;
						slist = (List<Scenery>) map.get("scenery");
						glist = (List<Guide>) map.get("guide");
						sCountlv.addAll(slist);
						gCountlv.addAll(glist);
						adapter.setData(sCountlv);
						dialog.dismiss();
					} else if (temp == 0) {
						dialog.dismiss();
						isFirst = !isFirst;
						Toast.makeText(SceneryListActivity.this,
								R.string.is_no_result, Toast.LENGTH_SHORT)
								.show();
					}
					break;
				}

				adapter.notifyDataSetChanged();

			}
		};
		// toast = DialogView.popToast(context, msg)
		context = this;
		title_text = (TextView) findViewById(R.id.title_text);
		scenery_search = (LinearLayout) findViewById(R.id.scenery_search);
		scenery_search_text = (EditText) findViewById(R.id.scenery_search_text);
		title_back = (LinearLayout) this.findViewById(R.id.title_back);
		rel_default_action = (RelativeLayout) this
				.findViewById(R.id.rel_default_action);
		dialog = DialogView.popDialog(this, R.string.isloading);
		adapter = new SceneryListAdapter(this);
		gNewlv = new ArrayList<Guide>();
		gCountlv = new ArrayList<Guide>();
		sNewlv = new ArrayList<Scenery>();
		glist = new ArrayList<Guide>();
		slist = new ArrayList<Scenery>();
		sCountlv = new ArrayList<Scenery>();
		listView = (XListView) findViewById(R.id.scenery_list);
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);

		title_text.setText(R.string.title_text_scenery);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				/*System.out.println("--------position----" + position + "、"
						+ sCountlv.get(position - 1));
				System.out.println("--------position----" + position + "、"
						+ gCountlv.get(position - 1));*/
				Intent intent = new Intent(SceneryListActivity.this,
						SceneryDetails.class);
				// Bundle bundle = new Bundle() ;
				intent.putExtra("scenery", sCountlv.get(position - 1));
				intent.putExtra("guide", gCountlv.get(position - 1));
				// intent.putExtras(bundle) ;
				startActivity(intent);

			}
		});

		scenery_search_text
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub

					}
				});
		scenery_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String searchName = scenery_search_text.getText().toString();
				if (searchName != null && scenery_search_text.length() > 0) {
					/*Toast.makeText(SceneryListActivity.this,
							"--1--" + scenery_search_text.length(),
							Toast.LENGTH_SHORT).show();*/
					loadDataBySearch(Constants.LISTVIEW_ACTION_SEARCH, handler,
							searchName);
				} else {
					Toast.makeText(SceneryListActivity.this,
							"请输入景点名称" + scenery_search_text.length(),
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SceneryListActivity.this.onBackPressed();
			}
		});

		rel_default_action.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadData(Constants.LISTVIEW_ACTION_FIRST, handler, 1);
			}
		});
	}

	/**
	 * @param action
	 * @param handler
	 * @param name
	 * @retur void
	 * @Description: 加载查询数据
	 */
	void loadDataBySearch(final int action, final Handler handler,
			final String name) {
		if (action == Constants.LISTVIEW_ACTION_SEARCH) {
			dialog.show();
		}
		new Thread(new Runnable() {
			Message message = new Message();
			Map<String, Object> map;
			String s;

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (action) {
				case Constants.LISTVIEW_ACTION_SEARCH:
					s = HttpUtil.httpGet(Constants.SEARCH_SCENERY_AND_GUIDE_URL
							+ name);
					System.out.println("---" + s);
					defaul_action = Constants.LISTVIEW_ACTION_SEARCH;
					map = ParseGson.parseSceneryGuide(s);
					status = (Integer) map.get("status");
					switch (status) {
					case 1:
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_SEARCH;
						break;

					case 0:
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_SEARCH;
						break;
					case Constants.LISTVIEW_ACTION_GET_ERROR:
						message.what = Constants.LISTVIEW_ACTION_GET_ERROR;
						break;
					}
					break;

				default:
					break;
				}
				handler.sendMessage(message);
			}
		}).start();
	}

	/**
	 * 
	 * @retur void
	 * @Description: 加载分页数据
	 */
	public void loadData(final int action, final Handler handler,
			final int pageNo) {

		if (action == Constants.LISTVIEW_ACTION_FIRST) {
			dialog.show();
		}

		new Thread(new Runnable() {

			Message message = new Message();
			Map<String, Object> map;
			String s;

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (action) {
				case Constants.LISTVIEW_ACTION_FIRST:
					// s = HttpUtil.httpGet(Constants.GET_SCENERY_AND_GUIDE_URL
					// + pageNo);
					// s = TestData.getJson() ;
					s = getCacheData(Constants.GET_SCENERY_AND_GUIDE_URL
							+ pageNo);
					defaul_action = Constants.LISTVIEW_ACTION_FIRST;
					System.out.println("---" + s);
					map = ParseGson.parseSceneryGuide(s);
					status = (Integer) map.get("status");
					if (status == Constants.LISTVIEW_ACTION_GET_ERROR) {
						// message.obj =
						message.what = Constants.LISTVIEW_ACTION_GET_ERROR;
					} else if (status == 1) {
						// gNewlv = (List<Guide>) map.get("guide") ;
						// sNewlv = (List<Scenery>) map.get("scenery") ;
						if (!ConfigCache
								.isExitCacheFile(Constants.GET_SCENERY_AND_GUIDE_URL
										+ pageNo)) {
							ConfigCache.setUrlCache(s,
									Constants.GET_SCENERY_AND_GUIDE_URL
											+ pageNo);
						}
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_FIRST;
					}
					// System.out.println("---1---"+gNewlv.size()+"---"+gNewlv.get(1))
					// ;
					// System.out.println("---2---"+sNewlv.size()+"---"+sNewlv.get(12))
					// ;
					break;
				case Constants.LISTVIEW_ACTION_SCROLL:
					s = HttpUtil.httpGet(Constants.GET_SCENERY_AND_GUIDE_URL
							+ pageNo);
					// s = TestData.getJson() ;
					defaul_action = Constants.LISTVIEW_ACTION_SCROLL;
					map = ParseGson.parseSceneryGuide(s);
					status = (Integer) map.get("status");
					switch (status) {
					case 1:
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_SCROLL;
						break;

					case 0:
						message.obj = map;
						message.what = Constants.LISTVIEW_ACTION_SCROLL;
						break;
					case Constants.LISTVIEW_ACTION_GET_ERROR:
						message.what = Constants.LISTVIEW_ACTION_GET_ERROR;
						break;
					}
					break;
				default:
					break;
				}
				handler.sendMessage(message);
			}
		}).start();

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		// overridePendingTransition(R.anim.out_to_left, R.anim.in_from_right);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		listView.stopRefresh();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (!isFirst) {
			// int pageIndex = count / Constants.PAGE_SIZE + 1;
			int pageIndex = count % Constants.PAGE_SIZE == 0 ? count
					/ Constants.PAGE_SIZE + 1 : count / Constants.PAGE_SIZE + 2;
			System.out.println("=================" + count + "/////"
					+ pageIndex);
			loadData(Constants.LISTVIEW_ACTION_SCROLL, handler, pageIndex);
		} else {
			loadData(Constants.LISTVIEW_ACTION_FIRST, handler, 1);
			if (!gCountlv.isEmpty() || !sCountlv.isEmpty()) {
				gCountlv.clear();
				sCountlv.clear();
			}
			isFirst = !isFirst;
		}

	}

	/**
	 * @param url
	 * @return
	 * @retur String
	 * @Description: 获取缓存数据
	 */
	public String getCacheData(String url) {
		String result = null;
		result = ConfigCache.getUrlCache(url);
		if (result == null) {
			result = HttpUtil.httpGet(url);
		}
		return result;
	}

}
